/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package crawler.post;

import crawler.common.ConfigFactory;
import crawler.common.FileUtil;
import crawler.common.PostData;
import crawler.common.StaticData;
import crawler.model.StaticModel;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author LT
 */
public class StaticCrawler {
 
    private static final Logger logger = Logger.getLogger(StaticCrawler.class);
    private static final Lock createLock_ = new ReentrantLock();
    private static StaticCrawler _instance = null;
    
    public static final String STATIC_UPLOAD_POST = ConfigFactory.getParam("upload", "upload_path") + ConfigFactory.getParam("upload", "upload_post");
    public static final String STATIC_URL_POST = ConfigFactory.getParam("static", "img") + ConfigFactory.getParam("upload", "upload_post");

    public static StaticCrawler getInstance() {
        if (_instance == null) {
            createLock_.lock();
            try {
                if (_instance == null) {
                    _instance = new StaticCrawler();

                }
            } finally {
                createLock_.unlock();
            }
        }
        return _instance;
    }
    public StaticData download(String srcURL, String desProj, String desSite){
        String fileName;
        String localPath = STATIC_UPLOAD_POST + desProj + "/" + desSite+ "/" ;
        fileName = FileUtil.download(srcURL, localPath);
        String localURL = STATIC_URL_POST + desProj + "/" + desSite  + "/" + fileName;
        StaticData staticData = new StaticData("0", srcURL, localURL, System.currentTimeMillis()/1000L);
        StaticModel staticModel = StaticModel.getInstance();
        staticModel.addStatic(staticData);
        return staticData;
    }
    public String crawImage(String srcURL, String desProj, String desSite){
        StaticData staticData = download(srcURL, desProj, desSite);
        if(staticData == null || staticData.getLocal() == null || staticData.getLocal().isEmpty()){
            return srcURL;
        }
        return staticData.getLocal();
    }
    public StaticData getImage(String srcURL, String desProj, String desSite){
        StaticData staticData = download(srcURL, desProj, desSite);
        if(staticData == null || staticData.getLocal() == null || staticData.getLocal().isEmpty()){
            return new StaticData(null, srcURL, srcURL, 0);
        }
        return staticData;
    }
}
